package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Волков Олег on 27.05.14.
 */

public class CharsetFilter implements Filter
{
    private String encoding;

    public void init(FilterConfig config) throws ServletException
    {
        encoding = config.getInitParameter("requestEncoding");
        if( encoding==null ) encoding="UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {

        if(null == request.getCharacterEncoding())
            request.setCharacterEncoding(encoding);
        /**
         * Set the default response content type and encoding
         */
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }

    public void destroy(){}

    public static class NoCacheFilter implements Filter {
        public void destroy() {
        }

        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            try {
                if (resp instanceof HttpServletResponse) {
                    HttpServletResponse httpresponse = (HttpServletResponse) resp;
                    // Set the Cache-Control and Expires header
                    httpresponse.setHeader("Cache-Control", "no-cache");
                    httpresponse.setHeader("Expires", "0");
                    // Print out the URL we're filtering
                    String name = ((HttpServletRequest) req).getRequestURI();
                    System.out.println("No Cache Filtering: " + name);
                }
                chain.doFilter(req, resp);
            } catch (IOException e) {
                System.out.println("IOException in NoCacheFilter");
                e.printStackTrace();
            } catch (ServletException e) {
                System.out.println("ServletException in NoCacheFilter");
                e.printStackTrace();
            }
        }


        public void init(FilterConfig config) throws ServletException {

        }

    }
}
